import { Component, OnInit, Input, SimpleChanges, Output, EventEmitter, OnChanges } from '@angular/core';
import { AlarmService } from 'app/pages/traffic-management/traffic-alert/alarm.service';
import { PublicService } from 'app/public/public.service';
import { SELECT_OPTIONS, SYSTEM_EVENT } from 'app/app.constants';
import * as moment from 'moment';
import { BullySubjectService, Bully } from 'app/shared/service';
import { differenceInCalendarDays } from 'date-fns';
import { MessagesService } from 'app/shared/service';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { AuthService } from 'app/auth/auth.service';

@Component({
    selector: 'itmp-historical-alert',
    templateUrl: './historical-alert.component.html',
    styleUrls: ['./historical-alert.component.css']
})
export class HistoricalAlertComponent implements OnInit, OnChanges {
    @Input() zoneList;
    pagination = {
        totalEle: 25,
        pageSize: 10,
        currentPage: 1,
        currentSize: 10
    };
    dateRange = [];
    dateRangeAck = [];
    totalEle = 0;
    listOfData = [];
    editingItem = '';
    renderHeader: any = [];
    queryCondition = {
        detectionTime: null,
        alertID: null,
        zoneID: null,
        roadName: null,
        alertSource: null,
        ackBy: null,
        ackTime: null,
        ackValue: null
    };
    toolbarList = [
        // { className: 'icon-CCTV' },
        { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' },
        { className: 'icon-xiazai' }
    ];
    alertSourceList: any = [{ label: 'All', value: null }, { label: 'TSC', value: 'TSC' }, { label: 'AID', value: 'AID' }];
    description: any = [];
    queryStartTime = null;
    queryEndTime = null;
    queryAckStartTime = null;
    queryAckEndTime = null;
    selectItem = null;
    queryData = null;
    isCreateTr = false;
    isShowVietName = false;
    isCrossRegion = false;
    @Output() isIrSelected = new EventEmitter();

    constructor(
        private alarmService: AlarmService,
        private pub: PublicService,
        private bully: BullySubjectService,
        private msg: MessagesService,
        private router: Router,
        private authService: AuthService,
        private message: NzMessageService
    ) {}

    ngOnChanges(changes: SimpleChanges) {
        this.bully.zoneListBehavior.subscribe(res => {
            this.zoneList = res['selectZoneList'];
            this.getAllList();
        });
    }

    ngOnInit() {
        this.renderHeader = this.alarmService.renderHeader();
        // this.description = this.alarmService.description();
        this.getSelectionList();
        // this.listOfData = this.alarmService.generateEvents(10);
        this.getAllList();
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.isShowVietName = true;
        } else {
            this.isShowVietName = false;
        }
    }

    getSelectionList() {
        this.description = this.pub.getSelectOptionsList(SELECT_OPTIONS.ALERT_TYPE).data;
    }

    // page change
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getAllList();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        this.pagination.currentPage = 1;
        this.getAllList();
    }

    getAllList() {
        const pageParam = {
            pageNo: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        const queryTimeRange = {
            startTime: this.queryStartTime,
            endTime: this.queryEndTime
        };
        const dateAckParam = {
            startTime: this.queryAckStartTime,
            endTime: this.queryAckEndTime
        };
        this.queryData = this.alarmService.formAlertData(this.renderHeader, queryTimeRange, dateAckParam, pageParam, this.zoneList);
        const qurey = this.alarmService.getHistoricalAlert(this.queryData);
        qurey.subscribe(
            (res: any) => {
                this.listOfData = res.data.list;
                this.pagination.totalEle = res.data.totalCount;
                this.pagination.currentSize = res.data.numberOfElements;
            },
            (error: any) => {}
        );
    }

    initData() {
        // this.queryCondition = {
        //     detectionTime: null,
        //     alertID: null,
        //     zoneID: null,
        //     roadName: null,
        //     alertSource: null,
        //     ackBy: null,
        //     ackTime: null,
        //     ackValue: null
        // };
        this.renderHeader.forEach(item => {
            item.key = null;
        });
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryAckStartTime = null;
        this.queryAckEndTime = null;
        this.selectItem = null;
        this.pagination = {
            totalEle: 25,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
    }

    refresh() {
        this.dateRange = [];
        this.dateRangeAck = [];
        this.initData();
        this.getAllList();
    }

    getTimeStamp() {
        const nowdate = new Date();
        nowdate.setMonth(nowdate.getMonth() - 3);
        const y = nowdate.getFullYear();
        const m = nowdate.getMonth() + 1;
        const d = nowdate.getDate();
        const formatwdate = y + '-' + m + '-' + d;
        return new Date(formatwdate).getTime();
    }

    onChange(result: Date): void {
        this.queryStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getAllList();
    }

    showDetail(item): void {
        this.editingItem = item.alertID;
        this.selectItem = item;
    }

    filterSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getAllList();
    }

    onAckChange(result: Date): void {
        this.queryAckStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryAckEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getAllList();
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };

    CreateIR() {
        if (!this.selectItem) {
            this.message.create('warning', 'Please select a record.');
            return;
        }
        if (this.selectItem.ackValue === 'true') {
            if (this.authService.isUserZoneChecked(this.selectItem.zoneID)) {
                this.isCreateTr = true;
            }
        } else {
            // 请选择一条ackValue为true的数据
            this.msg.error(`Please select a piece of data whose ackValue is true`);
        }
    }

    createIrCancel() {
        this.isCreateTr = false;
        this.isCrossRegion = false;
    }

    createIrOk() {
        // this.isIrSelected.emit(this.selectItem);
        this._ackVerifyHandle(this.selectItem);
        this.isCreateTr = false;
    }

    createIrOkForce() {
        this.ackVerifyHandleForce(this.selectItem);
        this.isCrossRegion = false;
    }

    private _ackVerifyHandle(data: any) {
        const zone = this.authService.isUserZoneChecked(data.zoneID);
        if (!zone) {
            return;
        }
        if (zone.isTemp) {
            this.isCrossRegion = true;
            return;
        }
        this.ackVerifyHandleForce(data);
    }

    // 统一发送事件
    ackVerifyHandleForce(data: any) {
        this.router.navigate(['/ccm/traffic-management/incident-record']);
        // 用BS发送创建的事件
        const bully: Bully = {
            type: SYSTEM_EVENT.CREATE_EVENT,
            data,
            fromGis: false
        };

        // 延迟发送BS, 避免resetBS带来的副作用
        setTimeout(() => {
            this.bully.setBSubject(bully);
        }, 500);
    }
}
